package com.theten52.demo.io;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义线程工厂
 *
 * @author wangjin
 * @date 2021/3/11
 */
public class NamedThreadFactory implements ThreadFactory {

    private final String threadName;

    public AtomicInteger atomicInteger = new AtomicInteger(0);

    public NamedThreadFactory() {
        this.threadName = "custom-thread-";
    }

    public NamedThreadFactory(String threadName) {
        this.threadName = threadName;
    }

    /**
     * Constructs a new {@code Thread}.  Implementations may also initialize
     * priority, name, daemon status, {@code ThreadGroup}, etc.
     *
     * @param r a runnable to be executed by new thread instance
     * @return constructed thread, or {@code null} if the request to
     * create a thread is rejected
     */
    @Override
    public Thread newThread(Runnable r) {
        return new Thread(r, threadName + atomicInteger.getAndIncrement());
    }
}
